package com.itjh.controller;

import com.itjh.annotaiton.Log;
import com.itjh.pojo.Dept;
import com.itjh.pojo.MyResponseResult;
import com.itjh.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门管理Controller
 */
@RestController
@RequestMapping("depts")
public class DeptController {
    @Autowired
    private DeptService deptService;

    //查询部门信息
    @GetMapping
    public MyResponseResult<List<Dept>> selectAll() {
        List<Dept> depts = deptService.selectAll();
        return MyResponseResult.success(depts);
    }


    //根据ID删除部门
    @Log
    @DeleteMapping("/{id}")
    public MyResponseResult<Object> deleteDeptById(@PathVariable Integer id) {
        int i = deptService.deleteById(id);
        return i >= 1 ? MyResponseResult.success(null) : MyResponseResult.error("删除失败!");
    }

    //新增部门信息
    @Log
    @PostMapping
    public MyResponseResult<Object> addDept(@RequestBody Dept dept) {
        int i = deptService.insertDept(dept);
        return i >= 1 ? MyResponseResult.success("添加成功!") : MyResponseResult.error("添加部失败!");
    }

    //修改部门信息
    //根据部门id查询部门回显
    @GetMapping("/{deptId}")
    public MyResponseResult<Object> getById(@PathVariable Integer deptId) {
        Dept dept = deptService.getById(deptId);
        return dept != null
                ? MyResponseResult.success(dept)
                : MyResponseResult.error(0,"查询失败", null);
    }

    @Log
    @PutMapping
    public MyResponseResult<Object> updateDeptById(@RequestBody Dept dept) {
        int i = deptService.updateDeptById(dept);
        return i >= 1 ? MyResponseResult.success("ID为 " + dept.getId() + " 的部门信息修改成功") : MyResponseResult.error("修改失败!");
    }
}
